package cc.customer.quartzTask;

import cc.customer.common.annotation.CronTag;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.SchoolHttpUtils;
import cc.customer.common.utils.Utils;
import cc.customer.common.utils.poi.HttpRespons;
import cc.customer.onschool.domain.OnSchoolResource;
import cc.customer.onschool.services.OnSchoolService;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

@CronTag("TaskSchoolServiceImpl")
public class TaskSchoolServiceImpl {
   private Logger log = LoggerFactory.getLogger(this.getClass());
   @Autowired
   private OnSchoolService onSchoolService;
   @Autowired
   private UserService userService;

   /**
    * 手动同步网校资源 带日期
    **/
   @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
   public void schoolSourceTime() throws Exception {
      String tokenurl = "https://auth.xlcwx.com/connect/token";
      String resourceurl = "https://systemcore.xlcwx.com/api/provider/students/new";
      Map<String, String> map = new HashMap<String, String>();
      map.put("client_id", "CRM.SystemCoreClient");
      map.put("client_secret", "aba01b02-00d3-4064-8545-012963827b26");
      map.put("grant_type", "client_credentials");
      map.put("scope", "JuXueSchool.SystemCore");
      int count = 0;

      int numall = 0;
      /**删除存在的网校资源,没有跟踪人**/
      int num = onSchoolService.deleteSchoolResource();
      log.error("同步客户系统网校资源-删除没有跟踪人的数据:" + num);

      /**查询所有有邀请码的用户**/
      List<MyUser> users = userService.findByCode();

      /**查询已经分配的资源用户**/
      List<String> listPhone = onSchoolService.selectSchoolPhone();

      try {
         /**获取token**/
         String token = SchoolHttpUtils.post(tokenurl, null, map, null);
         JSONObject json = JSONObject.parseObject(token);
         String access_token = json.getString("access_token");


         log.info("获取的网校的token:" + access_token);


         /**如果拿到**/
         if (!StringUtils.isEmpty(access_token)) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("Authorization", "Bearer " + access_token);
            /**发送请求**/
            for (; ; ) {
               Map<String, String> param = new HashMap<>();
               param.put("pageSize", "300");
               param.put("pageIndex", count + "");
               HttpRespons res = SchoolHttpUtils.sendGet(resourceurl, param, tokenMap);
               Vector<String> data = res.getContentCollection();
               if (!data.isEmpty()) {
                  String message = data.get(0);
                  JSONObject obj = JSONObject.parseObject(message);
                  String datas = obj.getString("data");
                  JSONArray js = JSONObject.parseArray(datas);
                  /**如果有数据**/
                  if (js.size() > 0) {
                     count++;
                     List<OnSchoolResource> list = new ArrayList<>();
                     for (int i = 0; i < js.size(); i++) {
                        JSONObject jn = js.getJSONObject(i);
                        String mobile = jn.getString("tel");
                        if (!listPhone.contains(mobile)) {
                           OnSchoolResource onSchoolResource = parseResource(jn, users);
                           list.add(onSchoolResource);
                        }
                     }
                     if (!list.isEmpty()) {
                        int numn = onSchoolService.batchInsertByCode(list);
                        numall += numn;
                        log.info("网校资源" + count + "批次导入成功：" + numn + "条，时间：" + DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
                     }
                  } else {
                     break;
                  }
               }
            }
         }
      } catch (Exception e) {
         throw new RuntimeException("更新失败：" + e.getMessage());
      }
      log.info("网校资源导入成功：" + numall + "条");
   }

   /**
    * 包装网站数据表情包
    **/
   private OnSchoolResource parseResource(JSONObject json, List<MyUser> users) {
      OnSchoolResource newbig = new OnSchoolResource();
      newbig.setOsUuid(Utils.getUUID());
      String name = FebsUtil.filterEmoji(json.getString("nickname"));
      newbig.setOsNickname(name);
      newbig.setOsEmail(json.getString("email"));
      newbig.setOsSex(json.getString("sex"));
      newbig.setOsCity(json.getString("province"));
      newbig.setOsZone(json.getString("city"));
      newbig.setOsMobile(json.getString("tel"));
      newbig.setOsQq(json.getString("qq"));
      newbig.setOsImportTime(DateUtil.getCurrentDate("yyyy-MM-dd"));
      newbig.setOsCreateTime(json.getString("registerTime").substring(0, 10));
      newbig.setOsDealStatus("0");
      newbig.setOsStage("1");
      newbig.setOsRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
      newbig.setOsRecent("同步网校资源");
      String code = json.getString("invitedByCode");
      for (MyUser user : users) {
         String codeMy = user.getByCode();
         if (codeMy.equals(code)) {
            /**所属客服*/
            newbig.setOsMyCustomer(user.getUserUuid());
            newbig.setOsMyCustomerName(user.getNickname());
            newbig.setOsDept(user.getDeptId().toString());
         }
      }
      return newbig;
   }


}
